<template>
  <div class="page-login">
    <div class="page-login_container">
      <h2 class="title">后台管理系统</h2>
      <el-form ref="formRef" :model="formData" :rules="formRules">
        <el-form-item prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="isloading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/api/users.js";
import { mapMutations } from "vuex";

export default {
  name: "login",

  data() {
    return {
      //表单数据
      formData: {
        username: "",
        password: "",
      },
      //表单校验规则
      formRules: {
        username: [{ required: true, message: "请输入用户名" }],
        password: [{ required: true, message: "请输入密码" }],
      },
      //登入按钮是否禁用
      isloading: false,
    };
  },
  methods: {
    ...mapMutations(["getname"]),
    //async   await  将异步代码转为同步代码
    //try  catch   捕获可能报错的代码
    async handleLogin() {
      try {
        //点击登入  先进行表单校验  检验通过进行下一步
        await this.$refs.formRef.validate();
        //发送请求
        login({
          adminname: this.formData.username,
          password: this.formData.password,
        })
          //获得数据
          .then((data) => {
            //改变登入按钮状态  防止在发送过程中连续点击
            this.isloading = true;
            console.log(data);
            //将token存入本地存储
            localStorage.setItem("token", data.data.token);
            this.getname(data);
            //跳转页面
            function getName(route) {
              let str = "";
              if (route.children) {
                str = getName(route.children[0]);
              } else {
                str = route.name;
              }

              return str;
            }

            this.$router.push({
              name: getName(this.$store.getters.getjurisdictionroute[0]),
            });
          })
          .catch(() => {})
          .finally(() => {
            //请求完全结束 恢复登入按钮状态
            this.isloading = false;
          });
      } catch (error) {
        throw error;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-login {
  height: 100%;
  overflow: hidden;
  background-color: pink;
}
.title {
  color: #fff;
  text-align: center;
}
.page-login_container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.el-form {
  padding: 32px 32px 14px;
  width: 320px;
  border-radius: 10px;
  background-color: #fff;
}

.el-button {
  width: 100%;
}
</style>
